package cn.jingzhuan.fm.ui.adapter

import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

abstract class BaseAdapterWrapper(var adapter: RecyclerView.Adapter<RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>(){

    /** view type : "上拉加载更多"  */
    private val ITEM_TYPE_LOAD = Integer.MAX_VALUE / 2
    private var wrapperHolder: WrapperHolder? = null
    private var mShowLoadItem = true

    // 加载更多视图
    abstract fun getLoadMoreItemLayoutId(viewType: Int): Int
    abstract fun setLoadMoreVisiable(binding: ViewDataBinding, show: Boolean)
    abstract fun setLoadTipText(binding: ViewDataBinding)
    abstract fun setLoadingText(binding: ViewDataBinding)

    // 创建视图
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == ITEM_TYPE_LOAD) {
            if (wrapperHolder == null) {
                var binding = DataBindingUtil.inflate<ViewDataBinding>(LayoutInflater.from(parent.context), getLoadMoreItemLayoutId(viewType), parent, false)
                wrapperHolder =  WrapperHolder(binding)
            }
            wrapperHolder!!
        } else {
            adapter.onCreateViewHolder(parent, viewType)
        }
    }

    override fun getItemCount(): Int = if (mShowLoadItem) adapter.itemCount + 1 else adapter.itemCount

    override fun getItemViewType(position: Int): Int {
        // 当显示"加载更多"条目, 并且位置是最后一个时, wrapper进行拦截
        return if (mShowLoadItem && position == itemCount - 1)
            ITEM_TYPE_LOAD// 注意要避免和原生adapter返回值重复
         else adapter.getItemViewType(position) // 其他情况交给原生adapter处理
    }


    // 允许显示"加载更多"item, 并且position为末尾时,拦截
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (mShowLoadItem && position == itemCount - 1) {
//            holder.itemView.visibility = View.GONE
        } else if (position < adapter.itemCount) {
            // 正常情况
            holder.itemView.visibility = View.VISIBLE
            adapter.onBindViewHolder(holder, position)
        }
    }


    fun setLoadItemVisibility(isShow: Boolean) {
        if (mShowLoadItem != isShow) {
            mShowLoadItem = isShow
            notifyDataSetChanged()
        }
    }

    fun setLoadItemState(isLoading: Boolean) {
        if (null != wrapperHolder) {
            if (isLoading) {
                setLoadingText(wrapperHolder!!.loadMoreBinding)
                setLoadMoreVisiable(wrapperHolder!!.loadMoreBinding,true)
            } else {
                setLoadTipText(wrapperHolder!!.loadMoreBinding)
                setLoadMoreVisiable(wrapperHolder!!.loadMoreBinding,false)
            }
        }
    }

    class WrapperHolder(var loadMoreBinding: ViewDataBinding ) : RecyclerView.ViewHolder(loadMoreBinding.root)
}